#include "hiconlistview.h"


#include <QScrollArea>
#include <QLayoutItem>
#include <QDebug>

HIconListView::HIconListView(QWidget *parent) : QFrame(parent),
    mScrollArea(new QScrollArea(this)),
    mCenter(new QWidget(this)),
    mMainLayout(new QGridLayout(mCenter))

{
    setContentsMargins(0, 0, 0, 0);
    QHBoxLayout* layout = new QHBoxLayout(this);
    layout->addWidget(mScrollArea);
    mCenter->setLayout(mMainLayout);
    mScrollArea->setFrameShape(QFrame::NoFrame);

    mViewMode = HIconItemView::IconMode;
    mSize = QSize(120, 120);
    mIconSize = QSize(96, 86);

    setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
}

void HIconListView::setItemSpcing(int spacing)
{
    mMainLayout->setSpacing(spacing);
}

HIconItemView::ViewMode HIconListView::viewMode() const
{
    return mViewMode;
}

void HIconListView::setViewMode(const HIconItemView::ViewMode &viewMode)
{
    mViewMode = viewMode;
}

QSize HIconListView::iconSize() const
{
    return mIconSize;
}

void HIconListView::setIconSize(const QSize &iconSize)
{
    mIconSize = iconSize;
}

QSize HIconListView::size() const
{
    return mSize;
}

void HIconListView::setSize(const QSize &size)
{
    mSize = size;
}

void HIconListView::setItems(const QList<HIconListViewItem> &items)
{
    mItems = items;
    updateUI();
}


void HIconListView::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
}

void HIconListView::updateUI()
{
    while (QLayoutItem *item = mMainLayout->takeAt(0)) {
        if (QWidget *widget = item->widget()) {
            widget->setParent(nullptr);
        }
        delete item;
    }
    QRect rect = this->rect();
    int w = 0, c = 0, r = 0;
    int index = 0;
    for (const HIconListViewItem& item : mItems) {
        HIconItemView* v = new HIconItemView(item, this);
        v->setSize(mSize);
        v->setIconSize(mIconSize);
        v->setViewMode(mViewMode);
        v->setVisible(true);
        v->setIndex(index++);
        connect(v, SIGNAL(itemClicked(int)), SIGNAL(itemClicked(int)));
        w += v->size().width();
        if (w > rect.width()) {
            w = 0;
            c = 0;
            r++;
        } else {
            c++;
        }
        mMainLayout->addWidget(v, r, c);
    }
    mScrollArea->setViewport(mCenter);
}
